import NP from 'number-precision'
import { Ref, isRef } from 'vue'

type WrapperRequestThis = Ref<boolean> | { submitting: boolean }

/**
 * 请求包装器
 * 当需要按钮loading时
 * @description // ! 被包装后 原函数类型校验可能会失效 请确认类型无误后 再包装
 */
export function wrapperRequest<A, R>(fn: (...args: A[]) => Promise<R>, wait = 300) {
  return function (this: WrapperRequestThis, ...args: A[]): Promise<R> {
    const context = this
    if (isRef(context)) {
      context.value = true
    } else {
      context.submitting = true
    }

    return new Promise(resolve => {
      setTimeout(function () {
        fn(...args)
          .then(resolve)
          .finally(() => {
            if (isRef(context)) {
              context.value = false
            } else {
              context.submitting = false
            }
          })
      }, wait)
    })
  }
}

/**
 *
 *
 * @export
 * @param {(number | undefined | null)} num
 * @param {boolean} [suffix=false] 是否添加后缀
 * @param {string} [text='%'] 后缀文本
 * @return {*}
 */
export function numberToPercentage(num: number | undefined | null, suffix = false, text = '%') {
  if (num === undefined || num === null) return '-'
  const val = NP.times(num, 100)
  if (suffix) return val + text
  return val
}
